# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
用户权限控制拦截器
"""
from django.http import JsonResponse
from django.shortcuts import HttpResponseRedirect

from web.models import User
from web.views.user import CheckLogin

try:
    from django.utils.deprecation import MiddlewareMixin  # Django 1.10.x
except ImportError:
    MiddlewareMixin = object  # Django 1.4.x - Django 1.9.x

# 管理员权限url
admin_url = [
    '/order/add/',
    '/order/update/',
    '/order/delete/',
    '/warehouse/add/',
    '/warehouse/update/',
    '/warehouse/delete/',
    '/task/submit/',
    '/task/delete/',
]
# 超级管理员权限url
superadmin_url = [
    '/user/get_users',
    '/user/set_user_level'
]
# 不进行拦截的url
notIntercept_url = [
    '/user/login/',
    '/user/register/',
    '/logs/read_log/'
]


class SimpleMiddleware(MiddlewareMixin):

    def process_request(self, request):
        if request.path not in notIntercept_url:  # 不进行拦截的url
            try:
                token = request.COOKIES.get('token')  # 首先检查是否登录了
                if token:
                    user_id = request.META.get('HTTP_USERID')   # 检查用户权限是否足够
                    user_level = User.objects.get(user_id=user_id, is_delete=0).user_level
                    if (user_level < 1 and request.path in admin_url) or \
                            (user_level < 2 and request.path in superadmin_url):
                        return JsonResponse({'code': '1', 'msg': "用户权限不足！"})
                    else:
                        pass
                else:
                    return JsonResponse({'code': '10010', 'msg': f"用户未登录！"})

            except Exception as e:
                return JsonResponse({'code': '1', 'msg': "过程出现异常，具体原因：" + str(e)})
